package com.edu.ujn.myh.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @作者 马永华
 * @日期 2010-4-15下午04:03:15
 * @版本 1.0.0
 */
public class FileOperation {

	// 产生随即文件名
	public static String getRandomFileName(String fileName) {
		// 获得文件名及文件后缀
		String name = "";
		fileName = fileName.trim();
		int a = fileName.lastIndexOf(".");
		String fileNameStr = fileName.substring(0, a);
		String typeStr = fileName.substring(a);
		Random random = new Random();
		String rname = new Long(random.nextLong()).toString();
		name = rname + "&File&" + fileNameStr + typeStr;
		return name;
	}

	// 获得目录的真实路径
	public static String getFileSavePath(HttpServletRequest request) {
		String path = request.getSession().getServletContext().getRealPath(
				"/fileUpload");

		return path;
	}

	// 保存文件
	public static boolean writeFile(File file, String path) {
		boolean flag = true;
		FileOutputStream fo = null;
		File fileOut = new File(path);
		FileInputStream fi = null;
		byte[] buffer = new byte[255];
		try {
			fo = new FileOutputStream(fileOut);
			fi = new FileInputStream(file);
			while ((fi.read(buffer)) != -1) {
				fo.write(buffer);
			}
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		} finally {
			try {
				fo.close();
				fi.close();
			} catch (IOException e) {
				flag = false;
				e.printStackTrace();
			}
		}
		return flag;
	}
}
